package com.wurao.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.wurao.entity.Blog;
import com.wurao.entity.Comment;
import com.wurao.lucene.BlogIndex;
import com.wurao.service.BlogService;
import com.wurao.service.CommentService;
import com.wurao.util.ExcelView;
import com.wurao.util.StringUtil;

/**
 * 博客信息管理Controller层
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/blog")
public class BlogController {

	@Resource
	private BlogService blogService;
	@Resource
	private CommentService commentService;
	

	private BlogIndex blogIndex=new BlogIndex();
	
	/**
	 * 请求博客详细信息
	 * @param id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/articles/{id}")
	public ModelAndView details(@PathVariable("id") Integer id,HttpServletRequest request)throws Exception{
		ModelAndView mav=new ModelAndView();
		Blog blog=blogService.findById(id);
		//关键字
		String keyWords=blog.getKeyWord();
		if(StringUtil.isNotEmpty(keyWords)){
			String arr[]=keyWords.split(" ");
			mav.addObject("keyWords",StringUtil.filterWhite(Arrays.asList(arr)));//把数组转换成集合，并去除 空格
		}else{
			mav.addObject("keyWords",null);
		}
		mav.addObject("blog",blog);
		//浏览次数
		blog.setClickHit(blog.getClickHit()+1);
		blogService.update(blog);
		//博客评论
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("blogId", blog.getId());
		map.put("state", 1);
//		map.put("start", 0);
//		map.put("pageSize", 3);
		List<Comment> list=commentService.list(map);
		mav.addObject("commentList", commentService.list(map));
		//上一篇或下一篇的博客
		mav.addObject("pageCode", this.getUpAndDownPageCode(blogService.getNextBlog(id), blogService.getLastBlog(id), request.getSession().getServletContext().getContextPath()));
		mav.addObject("pageTitle", blog.getTitle()+"_勿扰博客 Listen to wurao");
		mav.addObject("mainPage", "foreground/blog/view.jsp");
		mav.setViewName("mainTemp");
		return mav;
	}
	
	
	
	
	/**
	 * 获取上一篇博客和下一篇博客     
	 * @param lastBlog  
	 * @param nextBlog	
	 * @param projectContext	路径
	 * @return		标签
	 */
	private String getUpAndDownPageCode(Blog lastBlog,Blog nextBlog,String projectContext){
		StringBuffer pageCode=new StringBuffer();
		if(lastBlog==null || lastBlog.getId()==null){
			pageCode.append("<p>上一篇：没有了哦~</p>");
		}else{
			pageCode.append("<p>上一篇：<a href='"+projectContext+"/blog/articles/"+lastBlog.getId()+".html'>"+lastBlog.getTitle()+"</a></p>");
		}
			
		if(nextBlog==null || nextBlog.getId()==null){
			pageCode.append("<p>下一篇：没有了哦~</p>");
		}else{
			pageCode.append("<p>下一篇：<a href='"+projectContext+"/blog/articles/"+nextBlog.getId()+".html'>"+nextBlog.getTitle()+"</a></p>");
		}
		return pageCode.toString();
	}

	
	/**
	 * 根据关键字查询相关博客信息
	 * @param q
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/q")
	public ModelAndView search(@RequestParam(value="q",required=false) String q,
							   @RequestParam(value="page",required=false) String page,
							  HttpServletRequest request
			)throws Exception{
		int pageSize=12;
		
		
		ModelAndView mav=new ModelAndView();
		mav.addObject("pageTitle", "搜索关键字'"+q+"'结果页面_勿扰博客");
		mav.addObject("mainPage", "foreground/blog/result.jsp");
		
		List<Blog> blogList=blogIndex.searchBlog(q);//luncene关键字查询
		//关键字分页
		int count=(blogList.size() + pageSize - 1)/pageSize;
		if(StringUtil.isEmpty(page)|| Integer.parseInt(page)<=0 ){
			page="1";
		}else if(Integer.parseInt(page)>=count){
			page=count+"";
		}
		//三元运算符判断		到哪结束      
		Integer toIndex=blogList.size()>=Integer.parseInt(page)*pageSize?Integer.parseInt(page)*pageSize:blogList.size();
		//从哪开始
		Integer start=(Integer.parseInt(page)-1)*pageSize;
		mav.addObject("blogList", blogList.subList(start, toIndex));
		//调用自定义分页
		mav.addObject("pageCode", this.genUpAndDownPageCode(Integer.parseInt(page), blogList.size(), q, pageSize, request.getSession().getServletContext().getContextPath()));
		mav.addObject("q", q);
		mav.addObject("resultTotal", blogList.size());//查询的总条数
		mav.setViewName("mainTemp");
		return mav;
	}
	
	

	/**
	 * 获取上一页 		下一页代码
	 * @param page			页码
	 * @param totalNum		总记录数
	 * @param q				关键字
	 * @param pageSize		每页大小
	 * @param projectContext  路径
	 * @return
	 */
	private String genUpAndDownPageCode(Integer page,Integer totalNum,String q,Integer pageSize,String projectContext){
		//判断页数是否为能取余数，不能取余就加一页显示
		long totalPage=totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
		StringBuffer pageCode=new StringBuffer();
		if(totalPage==0){
			return "未查询到数据";
		}else{
			pageCode.append("<nav>");
				pageCode.append(" <ul class='pager'>");
					//如果页数小于1不进行任何操作，大于1以上都能显示上一页
					if(page>1){
						pageCode.append("<li ><a href='"+projectContext+"/blog/q.html?page="+(page-1)+"&q="+q+"'>上一页</a></li>");
					}else{
						pageCode.append("<li class='disabled'><a href=''>上一页</a></li>");
					}
					//如果页数大于总页数就不显示下一页
					if(page<=totalPage){
						pageCode.append("<li ><a href='"+projectContext+"/blog/q.html?page="+(page+1)+"&q="+q+"'>下一页</a></li>");
					}else{
						pageCode.append("<li class='disabled'><a href=''>下一页</a></li>");
					}
				pageCode.append("</ul>");
			pageCode.append("</nav>");
		}
		return pageCode.toString();
	}
	
	
	/**
	 * 文件导出
	 * @param model
	 * @return
	 */
	@RequestMapping("/testExcel")
	public ModelAndView testExcel(ModelMap model){
		Map<String,Object> map=new HashMap<>();
		map.put("start", 0);
		map.put("size", 10);
		List<Blog> data=blogService.listBlog(map);
		String[] headers={"编号","博客标题","发布日期","查看次数","博客内容"};
		String[] properties = {"id","title","releaseDate","clickHit","content"};
		
		for (Blog blog : data) {
			if(StringUtil.isNotEmpty(blog.getContent())){
				blog.setContent(delHTMLTag(blog.getContent()));
				if(blog.getContent().length()>32000){
					blog.setContent(blog.getContent().substring(0, 32000)+"......");
				}
			}
		}
		//设置单元格宽度
		Integer[] widths = {1000*5, 1000*5, 1000*5,1000*5,1000*5};
		return exportExcel(data, headers, properties, widths, model);
	}
	
	/**
	  * 除去标签工具
	  */
	 public static String delHTMLTag(String htmlStr){ 
	        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 
	        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 
	        String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式 
	         
	        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE); 
	        Matcher m_script=p_script.matcher(htmlStr); 
	        htmlStr=m_script.replaceAll(""); //过滤script标签 
	        
	        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE); 
	        Matcher m_style=p_style.matcher(htmlStr); 
	        htmlStr=m_style.replaceAll(""); //过滤style标签 
	         
	        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); 
	        Matcher m_html=p_html.matcher(htmlStr); 
	        htmlStr=m_html.replaceAll(""); //过滤html标签 
	        
	        // <p>段落替换为换行 
	        htmlStr = htmlStr.replaceAll("<p .*?>", "\r\n"); 
			// <br><br/>替换为换行 
	        htmlStr = htmlStr.replaceAll("<br\\s*/?>", "\r\n"); 
			// 去掉其它的<>之间的东西 
	        htmlStr = htmlStr.replaceAll("\\<.*?>", ""); 
	        //自定义
	        htmlStr = htmlStr.replaceAll("&nbsp;", " "); 
	        htmlStr = htmlStr.replaceAll("&lt;", " "); 
	        htmlStr = htmlStr.replaceAll("&gt;", " "); 
	        htmlStr = htmlStr.replaceAll("&quot;", " "); 
	        htmlStr = htmlStr.replaceAll("&#39;", " "); 
			// 还原HTML
			// content = HTMLDecoder.decode(content); 
	        return htmlStr.trim(); //返回文本字符串 
	    } 
	 
	
	/*****
	 * 导出Excel
	 * @param data 获取要导出的数据
	 * @param header 设置标题
	 * @param widths 设置列宽
	 * @param properties 设置单元格取值
	 * @param model
	 * @return 744111
	 */
	public ModelAndView exportExcel(List<?> data, String[] header, String[] properties, Integer[] widths, ModelMap model) {
		// 设置导出表格名
		String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
				+ ".xls";
		// 类型转换
		// Converter[] converters = {Double.class,Date.class};
		// 附加内容
		String[] contents = new String[3];
		contents[0] = "";
		contents[1] = "导出人" + ": wurao";
		contents[2] = "生成日期" + ": " + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		// 调用ExcelView工具类生成Excel并导出
		return new ModelAndView(new ExcelView(filename, null, properties,
				header, widths, null, data, contents), model);
	}
	
	
	/**
	 * js在线聊天室
	 * @param model
	 * @return
	 */
	@RequestMapping("/qq")
	public String qq(ModelMap model){
		return "other/qq/index";
	}
	
	
	/**
	 * vip视频解析
	 * @param model
	 * @return
	 */
	@RequestMapping("/vip")
	public String vipView(ModelMap model){
		return "redirect:/other/vip/index.html";
	}


	/**
	 * music解析
	 * @param model
	 * @return
	 */
	@RequestMapping("/music")
	public String musicView(ModelMap model){
		return "redirect:http://music.junyuewl.com/?tdsourcetag=s_pcqq_aiomsg";
	}

}
